package com.ruoyi.passenger.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.order.HttpClientUtil;
import com.ruoyi.management.basics.service.ITEmployeeMerService;
import com.ruoyi.management.basics.vo.DriverMerListVo;
import com.ruoyi.management.statistical.driversign.service.ITDriverSignService;
import com.ruoyi.passenger.order.domain.TOrder;
import com.ruoyi.passenger.order.service.ITOrderService;
import com.ruoyi.passenger.pay.ro.PayParam;
import com.ruoyi.passenger.pay.service.IPayService;
import com.ruoyi.passenger.pay.util.PayUtils;
import com.ruoyi.passenger.pay.vo.GetDriverSignVO;
import com.ruoyi.passenger.pay.vo.PayLogsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 付款业务层处理
 *
 * @author ruoyi
 * @date 2021-12-01
 */
@Service
public class PayServiceImpl implements IPayService {

    @Autowired
    private ITDriverSignService tDriverSignService;

    @Autowired
    private ITEmployeeMerService tEmployeeMerService;

    @Autowired
    private ITOrderService tOrderService;

    @Value("${pay.params.curCode}")
    private String curCode;

    @Value("${pay.params.txCode}")
    private String txCode;

    @Value("${pay.params.bankURL}")
    private String bankURL;

    @Value("${pay.params.qupwd}")
    private String qupwd;


    /**
     * 获取第一次支付地址
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getPayUrl(PayParam param,String type) {

        AjaxResult ajax = AjaxResult.success();;

        String carNo = param.getCarNo();

        //获取当前车辆驾驶员，根据该车最后一次打卡信息
        GetDriverSignVO signVO = tDriverSignService.getDriverSignVO(carNo);
        if (null != signVO)
        {
            ajax = AjaxResult.success();
            System.out.println("当前驾驶员 :"+signVO.getEmployeeName()+"; 打卡时间："+signVO.getSignTime());
            Long employeeId = signVO.getEmployeeId();
            //根据驾驶员id信息获取驾驶员商户信息
            DriverMerListVo driverMer = tEmployeeMerService.getDriverMerByEmployeeId(employeeId);

            if (null != driverMer)
            {
                //获取第一次支付接口地址
                ajax = PayUtils.sendPayUrlInfo(driverMer,param.getPayment()+"",curCode,txCode,bankURL,type);
                String payOrderId = String.valueOf(ajax.get("orderId"));
                //创建订单
                TOrder order =  new TOrder();
                order.setOrderDate(new Date());//订单时间
                order.setAmount(param.getPayment());//订单金额
                order.setEmployeeId(signVO.getEmployeeId());//驾驶员id
                order.setEmployeeName(signVO.getEmployeeName());//驾驶员姓名
                order.setCompanyId(signVO.getCompanyId());//企业 id
                order.setCarNo(signVO.getCarNo());//车牌号
                order.setPayStatus("2");//支付状态，未支付
                order.setIsSync(0);//未同步行程数据
                order.setPayOrderId(payOrderId);//支付订单id
                order.setPlatform(param.getPlatform());//支付平台
                order.setPlatformId(param.getOpenid());//用户id
                String openCode = param.getOpencode();
                order.setPlatformId(param.getOpenid());//临时
                ajax.put("order",order);
                return ajax;

            }else {
                ajax.put("result","error");
                ajax.put("msg","获取驾驶员商户信息失败，请选择其他支付方式");
            }

        }else {
            ajax.put("result","error");
            ajax.put("msg","获取驾驶员信息失败，请选择其他支付方式");
        }
        return ajax;

    }

    /**
     * 根据第一次支付地址获取第二次支付地址
     * @param payUrl
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getQrUrl(String payUrl,TOrder order) {
        AjaxResult ajax = AjaxResult.success();;
        String ret = HttpClientUtil.httpGet(payUrl, "UTF-8");
        System.out.println("第二次调用返回url::"+ret);
        if (null != ret && !"".equals(ret))
        {
            JSONObject payObject = JSONObject.parseObject(ret);
            if ("true".equals(payObject.getString("SUCCESS")))
            {
               ajax.put("qrUrl",payObject.getString("QRURL"));
               ajax.put("result","success");
               ajax.put("orderId",order.getId());
               //保存订单信息
                tOrderService.saveOrder(order);
            }
        }else {
            ajax.put("result","error");
            ajax.put("msg","支付失败，请选择其他支付方式");
        }

        return ajax;
    }

    /**
     * 获取支付结果更新订单信息
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getPayResult(PayParam param) {

        //查询订单
        String payOrderId = param.getPayOrderId();
        TOrder order =  tOrderService.getOrderByPayOrderId(payOrderId);

        //获取驾驶员商户信息
        if (null != order)
        {
            DriverMerListVo driverMer = tEmployeeMerService.getDriverMerByEmployeeId(order.getEmployeeId());

            //获取支付结果
            if ("2".equals(order.getPayStatus()))
            {
                PayLogsVO vo = PayUtils.sendQryResult(driverMer, bankURL, payOrderId, qupwd);
                String payResult = vo.getPayResult();
                order.setPayStatus(payResult);

                //更新数据库
                if ("0".equals(payResult) || "1".equals(payResult))
                {
                    order.setPayStatus(payResult);
                }else {
                    order.setPayStatus("3");
                }
                //更新
                tOrderService.updatePayStatus(payOrderId, order.getPayStatus());
            }
        }
        return AjaxResult.success(order);
    }


    /**
     * 获取订单支付状态，1-支付成功，0-支付失败，3-查询失败
     * @param payOrderId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayLogsVO getPayResultForTask(String payOrderId) {
        PayLogsVO vo = new PayLogsVO();
        //查询订单
        TOrder order =  tOrderService.getOrderByPayOrderId(payOrderId);

        //获取驾驶员商户信息
        if (null != order)
        {
            DriverMerListVo driverMer = tEmployeeMerService.getDriverMerByEmployeeId(order.getEmployeeId());

            //获取支付结果
            vo = PayUtils.sendQryResult(driverMer, bankURL, payOrderId, qupwd);
            String statusCode = vo.getPayResult();
            if ("0".equals(statusCode) || "1".equals(statusCode))
            {
                vo.setPayResult(statusCode);
                return vo;
            }
        }
        vo.setPayResult("3");
        return vo;
    }

    /**
     * 保存驾驶员营运信息
     */
    public void saveServiceStatics()
    {

    }
}
